package com.tanhua.dubbo.server.api;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.pojo.Visitors;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Date;
import java.util.List;

@Service(version = "1.0.0")
@Slf4j
public class VisitorsApiImpl implements VisitorsApi {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    RecommedApi recommedApi;

    private static final String VISITOR_REDIS_KEY = "VISITOR_USER";

    /**
     * 保存访客数据
     *
     * @param userId        我的id
     * @param visitorUserId 访客id
     * @param from          来源
     * @return
     */
    @Override
    public String saveVisitor(Long userId, Long visitorUserId, String from) {
        if (!ObjectUtil.isAllNotEmpty(userId, visitorUserId, from)) {
            return null;
        }
        String toDay = DateUtil.today();
        Long minDate = DateUtil.parseDateTime(toDay + " 00:00:00").getTime();
        Long maxDate = DateUtil.parseDateTime(toDay + " 23:59:59").getTime();

        Query query = Query.query(Criteria.where("userId").is(userId).and("visitorUserId").is(visitorUserId)
                .andOperator(Criteria.where("date").gte(minDate), Criteria.where("date").lte(maxDate)));
        long count = mongoTemplate.count(query, Visitors.class);
        if (count > 0) {
            return null;
        }
        //封装访客信息,保存访客信息
        Visitors visitors = new Visitors();
        visitors.setScore(recommedApi.getFatcvalue(userId, visitorUserId));
        visitors.setDate(System.currentTimeMillis());
        visitors.setFrom(from);
        visitors.setId(ObjectId.get());
        visitors.setUserId(userId);
        visitors.setVisitorUserId(visitorUserId);
        Visitors save = mongoTemplate.save(visitors);
        if (save != null) {
            log.info("保存成功!");
        }
        return visitors.getId().toHexString();
    }

    /**
     * 查询我的访客数据，存在2种情况：
     * 1. 我没有看过我的访客数据，返回前5个访客信息
     * 2. 之前看过我的访客，从上一次查看的时间点往后查询5个访客数据
     *
     * @param userId
     * @return
     */
    @Override
    public List<Visitors> queryMyVisitor(Long userId) {
        Long date = Convert.toLong(redisTemplate.opsForHash().get(VISITOR_REDIS_KEY, StrUtil.toString(userId)));

        PageRequest pageRequest = PageRequest.of(0, 5, Sort.by(Sort.Order.desc("date")));
        Query query = Query.query(Criteria.where("userId").is(userId)).with(pageRequest);
        if (ObjectUtil.isNotEmpty(date)) {
            query.addCriteria(Criteria.where("date").gte(date));
        }
        List<Visitors> visitors = mongoTemplate.find(query, Visitors.class);
        for (Visitors visitor : visitors) {
            Double fatcvalue = recommedApi.getFatcvalue(userId, visitor.getVisitorUserId());
            if (fatcvalue == null) {
                fatcvalue = 88d;
            }
            visitor.setScore(fatcvalue);
        }
        redisTemplate.opsForHash().put(VISITOR_REDIS_KEY, StrUtil.toString(userId), Convert.toStr(new Date().getTime()));
        return visitors;
    }

    /**
     * 查询我的所有访客数据:采用分页的形式
     *
     * @param userId
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public List<Visitors> queryMyVisitorAll(Long userId, Integer page, Integer pageSize) {
        PageRequest pageRequest = PageRequest.of(page, pageSize, Sort.by(Sort.Order.desc("date")));
        Query query = Query.query(Criteria.where("userId").is(userId)).with(pageRequest);
        List<Visitors> visitors = mongoTemplate.find(query, Visitors.class);
        for (Visitors visitor : visitors) {
            Double fatcvalue = recommedApi.getFatcvalue(userId, visitor.getVisitorUserId());
            if (fatcvalue == null) {
                fatcvalue = 88d;
            }
            visitor.setScore(fatcvalue);
        }
        return visitors;


    }


}
